package com.bupt.websocket.utils;

import com.bupt.websocket.bean.WebMessage;
import com.bupt.websocket.controller.UserController;
import com.jyt.message.Message;
import com.jyt.message.MessageConfig;
import com.jyt.message.MessageListener;
import com.jyt.message.MessageServerTcpClient;
import com.jyt.util.ArgumentString;
import com.jyt.util.MyDate;
import com.jyt.util.MyPrint;
import com.jyt.util.MySerializable;

import java.io.IOException;
import java.io.Serializable;
import java.net.SocketException;
import java.util.Scanner;

/**
 * Created by ikariyui on 2018/1/28.
 * 临时性客户端；
 * 用来处理request请求；
 */
public class DisposableClient extends MessageServerTcpClient {

    public String bmessage ="error";
    ThreadLocal<String> backmessage =  new ThreadLocal<>();
    boolean flag =true;

    public DisposableClient(String server_ip, String server_name, String entityName, String type) {
        super(server_ip, server_name,entityName);
        addListener(type,new WebResponseListener());
    }



    @Override
    public void work()
    {
        this.run();

    }

    public String workString(){
        this.run();
        return bmessage;
    }

    @Override
    public void run()
    {
        Thread.currentThread().setName("message_client_"+entity_list[0]);
        int count = 0;

        try {
            while (flag) {
                //receive();
                Message m = null;
                m = receive();
                synchronized (list) {
                    if (m != null) {
                        list.add(m);
                        m = null;
                        count = 0;
                        flag = false;
                        perform();
                    } else {
                        count++;
                        if (level == 0) {
                            wait_time_0(count);
                        } else if (level == 1) {
                            wait_time_1(count);

                        } else if (level == 2) {
                            wait_time_2(count);
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(super.theSocket!=null) {
                    super.theSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void perform()
    {
        //while (list.size()<=0){}

        Message m = list.remove(0);
        String type = m.getType();
        if(type.equals("kill")&&m.getType().equals("msg"))
        {
            MyPrint.print("收到系统的要求退出信息！", new Exception());
            System.exit(0);
        }

        MessageListener l = handler.get(type);
        if(l==null)
        {
            MyPrint.print("This WebMessage not register for listener:"+m.toString(),new Exception());
        }
        else{
            //		MyPrint.print("Begin to process message", new Exception());
            l.messagePerformed(m);
            //m = null;
        }
        String s = (String) MySerializable.bytes_object(m.getContent());
        bmessage = s;
        this.backmessage.set(s);
        System.out.print("******response********\n"+s);

    }


    public class WebResponseListener implements MessageListener
    {
        public void messagePerformed(Message message)
        {
            String field = "**************\n%1 from %2 \n%3\n**************";
            String time_str = MyDate.f2(message.getCreated());
            String to = message.getTo();
            String from = message.getFrom();
            byte[] content1 = message.getContent();
            Serializable serializable = MySerializable.bytes_object(content1);
            String serializable1 = (String) serializable;
            String content = (String) MySerializable.bytes_object(message.getContent());
            String[] ss = new String[]{time_str,from,content};
            String result = ArgumentString.replace(field,ss);

            //System.out.println(result);


            //sendMessage(to, "{\"from\":\""+from+"\",\"message\":\""+content+"\",\"to\":\""+to+"\"}");
            System.out.println("================min=======================");

        }

    }

        public static void main(String[] args) {
            DisposableClient ca=new DisposableClient(
                    "127.0.0.1",
                    MessageConfig.server_name,
                    "ClientWebSingle",
                    "msg");
            ca.register("ClientWebSingle");
            //ca.work();

            Scanner sc = new Scanner(System.in);
            String str = null;
            //while (true) {
                str = sc.nextLine();
                byte[] bs;
                bs = MySerializable.object_bytes(str);
                Message msg = new Message("ClientWebSingle","clientB","msg",bs);
                ca.send(msg);
            //}

            //测试
            //ca.work();
            //测试2
            String s = ca.workString();
            System.out.println("#########"+s+"########");
        }
}

